package ar.edu.itba.it.paw.web.filter;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import ar.edu.itba.it.paw.domain.User;
import ar.edu.itba.it.paw.repo.UserRepo;

@Component
public class UserFilter extends GenericFilterBean{
	
	private UserRepo userRepo;
	
	@Autowired
	public UserFilter(UserRepo userRepo){
		this.userRepo = userRepo;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
		throws IOException, ServletException {
		
		String url = ((HttpServletRequest)request).getRequestURL().toString();
		String suburl = url.substring(url.lastIndexOf('/')+1, url.length());
		ArrayList<String> tobeFiltered = new ArrayList<String>();
		tobeFiltered.add("editProduct"); tobeFiltered.add("editForm"); tobeFiltered.add("addProduct");
		tobeFiltered.add("categoryTransaction");
		tobeFiltered.add("editUser");
		
		HttpSession sesion = ((HttpServletRequest)request).getSession();
		
		Integer user_id = (Integer) sesion.getAttribute("usuario");
		User user = null;
		if( user_id != null && user_id > 0){
			user = userRepo.getUser(user_id);
		}
		
		if ((sesion != null && user != null) || !tobeFiltered.contains(suburl)) {
			/*esta sentencia es para ejecutar el servlet*/
			chain.doFilter(request, response);
			return;
		}
		
		((HttpServletResponse) response).sendRedirect(((HttpServletRequest) request).getContextPath() + "/bin/user/index?red=1");
	}
	
	@Override
	public void destroy() {}
	
}
